package com.cross.test.util;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.dom4j.DocumentException;


public class DataBaseHelper {
	public static void main(String[] args) {

	}

	private static String dbJdbc = null;

	private static String dbUser = null;

	private static String dbPwd = null;

	private static int max;

	private static long wait;

	private static String driver = null;

	private static Class driverClass = null;

	private static ObjectPool connectionPool = null;

	public static Map<String, ObjectPool> map = null;

	public DataBaseHelper() {
	}

	/** */
	/**
	 * 初始化数据源
	 */
	private static synchronized void initDataSource() {
		// 驱动数据源
		if (driverClass == null) {
			try {
				driverClass = Class.forName(driver);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	/** */
	/**
	 * 连接池启动
	 * 
	 * @throws Exception
	 */
	public static void StartPool(String poolname, String dbJdbc, String dbUser,
			String dbPwd, int max, long wait) {
		// 初始化数据源
		initDataSource();
		// 如果连接池为空
		if (connectionPool != null) {
			ShutdownPool();
		}
		try {
			connectionPool = new GenericObjectPool(null, max, (byte) 1, wait);
			ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
					dbJdbc, dbUser, dbPwd);
			PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
					connectionFactory, connectionPool, null, null, false, true);
			Class.forName("org.apache.commons.dbcp.PoolingDriver");
			PoolingDriver driver = (PoolingDriver) DriverManager
					.getDriver("jdbc:apache:commons:dbcp:");
			driver.registerPool(poolname, connectionPool);
			map.put(poolname, connectionPool);
			System.out.println("Create " + poolname
					+ " for Database Connection Succees.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** */
	/**
	 * 释放连接池
	 */
	public static void ShutdownPool() {
		try {
			PoolingDriver driver = (PoolingDriver) DriverManager
					.getDriver("jdbc:apache:commons:dbcp:");
			driver.closePool("dbpool");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/** */
	/**
	 * 打印连接池状态
	 */
	public static String GetPoolStats(String poolname) {

		StringBuffer stat = new StringBuffer();
		try {
			PoolingDriver driver = (PoolingDriver) DriverManager
					.getDriver("jdbc:apache:commons:dbcp:");
			ObjectPool connectionPool = driver.getConnectionPool(poolname);

			stat.append("-- Active Connection: ");
			stat.append(connectionPool.getNumActive());
			stat.append(" ,");
			stat.append("Free Connection: ");
			stat.append(connectionPool.getNumIdle());
			stat.append(" . --");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stat.toString();
	}

	/** */
	/**
	 * 取得连接池中的连接
	 * 
	 * @return
	 * @throws DocumentException 
	 * @throws FileNotFoundException 
	 */
	public synchronized static Connection getDbConnection(String poolname) throws FileNotFoundException, DocumentException {
		Connection conn = null;
		if (map == null) {
			System.out.println("map null");
			map = new HashMap<String, ObjectPool>();
		}
		if (map.get(poolname) == null) {
			init(poolname);// 初始化基本数据
			StartPool(poolname, dbJdbc, dbUser, dbPwd, max, wait);
		}
		try {
			conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"
					+ poolname);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	private static void init(String poolname) throws DocumentException, FileNotFoundException {
		List<BaseConnBean> pools = ConfigXml.read();
		for (BaseConnBean baseConnBean : pools) {
			if (baseConnBean.getName().equals(poolname)) {
				dbJdbc = baseConnBean.getJdbcurl();
				dbUser = baseConnBean.getUsername();
				dbPwd = baseConnBean.getPassword();
				max = baseConnBean.getMax();
				wait = baseConnBean.getWait();
				driver = baseConnBean.getDriver();
			}

		}
	}

	public static void close(Connection c) {
		try {
			if (c != null)
				c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
